/*
	Работа с SD картой
*/
//#include "defines.h"

#include <RTL.h>
#include <LPC17xx.h>
#include <stdio.h>
#include <rl_usb.h>
#include <string.h>
#include "File_Config.h"
#include "sd.h"

FAT_VI *mc0;    
Media_INFO info;
extern SPI_DRV      spi0_drv;

U8 media, sd_ok;

/*
	Инициализация SD карты
*/
U8 sd_init()
{
	U32 retv;
	
	/*//Настройка SD карты как USB MASS STORAGE
	usbd_init();                          
  usbd_connect(__TRUE); 
	mc0 = ioc_getcb (NULL);
  sd_ok = (!ioc_init (mc0));
  if (sd_ok)
	{
    ioc_read_info (&info, mc0);
  }*/
	
		//Настройка SD карты для доступа к ней из нашей программы
	retv = finit(NULL);
	if (retv==0)
		printf("SD Card ready\r\n");
	else if (retv==1)
		printf("SD Card not inserted\r\n");
	else
		printf("SD Card is Unformatted\r\n");
	
	return !retv;
	
}

/*
	Работа с флэшкой
*/
void sd_prc(void)
{
	//Проверяем -вставлена ли флэшка
	
	if (media ^ (spi0_drv.CheckMedia() & M_INSERTED)) 
	{
      media &= 1;
      media ^= 1;
      if (media) 
			{
				
				printf("SD inserted\r\n");
				if (!sd_ok)
					sd_ok = sd_init();
			}
			else
			{
				sd_ok=0;
				printf("SD removed\r\n");
			}
	}
	return;			
	if (media ^ (spi0_drv.CheckMedia() & M_INSERTED)) 
	{
      media &= 1;
      media ^= 1;
      if (media) {
				//карта вставлена
        if (!sd_ok) {
          sd_ok = (!ioc_init (mc0));
        }
        if (sd_ok) {
          ioc_read_info (&info, mc0);
          usbd_msc_init ();
          printf("SD Card ok!\r\n");
        } else {
          printf("SD Card not ok!\r\n");
        }
      } else {
        //Карта вынута
        sd_ok = 0;
        printf("SD Card missing!\r\n");
        USBD_MSC_MediaReady = __FALSE;
      }
	}
}

void cmd_dir (char *par) {
  U64 fsize;
  U32 files,dirs,i;
  char temp[32],*mask,*next,ch;
  FINFO info;

  /*mask = get_entry (par, &next);
  if (mask == NULL) {
    mask = "*.*";
  }*/
	mask = par;

  printf ("\nFile System Directory...");
  files = 0;
  dirs  = 0;
  fsize = 0;
  info.fileID  = 0;
  while (ffind (mask,&info) == 0) {
    if (info.attrib & ATTR_DIRECTORY) {
      i = 0;
      while (strlen((const char *)info.name+i) > 41) {
        ch = info.name[i+41];
        info.name[i+41] = 0;
        printf ("\n%-41s", &info.name[i]);
        info.name[i+41] = ch;
        i += 41;
      }
      printf ("\n%-41s    <DIR>       ", &info.name[i]);
      printf ("  %02d.%02d.%04d  %02d:%02d",
               info.time.day, info.time.mon, info.time.year,
               info.time.hr, info.time.min);
      dirs++;
    }
    else {
      dot_format (info.size, &temp[0]);
      i = 0;
      while (strlen((const char *)info.name+i) > 41) {
        ch = info.name[i+41];
        info.name[i+41] = 0;
        printf ("\n%-41s", &info.name[i]);
        info.name[i+41] = ch;
        i += 41;
      }
      printf ("\n%-41s %14s ", &info.name[i], temp);
      printf ("  %02d.%02d.%04d  %02d:%02d",
               info.time.day, info.time.mon, info.time.year,
               info.time.hr, info.time.min);
      fsize += info.size;
      files++;
    }
  }
  if (info.fileID == 0) {
    printf ("\nNo files...");
  }
  else {
    dot_format (fsize, &temp[0]);
    printf ("\n              %9d File(s)    %21s bytes", files, temp);
  }
  dot_format (ffree(""), &temp[0]);
  if (dirs) {
    printf ("\n              %9d Dir(s)     %21s bytes free.\n", dirs, temp);
  }
  else {
    printf ("\n%56s bytes free.\n",temp);
  }
}

/*----------------------------------------------------------------------------
 *        Process input string for long or short name entry
 *---------------------------------------------------------------------------*/
char *get_entry (char *cp, char **pNext) {
  char *sp, lfn = 0, sep_ch = ' ';

  if (cp == NULL) {                           /* skip NULL pointers          */
    *pNext = cp;
    return (cp);
  }

  for ( ; *cp == ' ' || *cp == '\"'; cp++) {  /* skip blanks and starting  " */
    if (*cp == '\"') { sep_ch = '\"'; lfn = 1; }
    *cp = 0;
  }
 
  for (sp = cp; *sp != CR && *sp != LF; sp++) {
    if ( lfn && *sp == '\"') break;
    if (!lfn && *sp == ' ' ) break;
  }

  for ( ; *sp == sep_ch || *sp == CR || *sp == LF; sp++) {
    *sp = 0;
    if ( lfn && *sp == sep_ch) { sp ++; break; }
  }

  *pNext = (*sp) ? sp : NULL;                 /* next entry                  */
  return (cp);
}

/*----------------------------------------------------------------------------
 *        Print size in dotted fomat
 *---------------------------------------------------------------------------*/
void dot_format (U64 val, char *sp) {

  if (val >= (U64)1e9) {
    sp += sprintf (sp,"%d.",(U32)(val/(U64)1e9));
    val %= (U64)1e9;
    sp += sprintf (sp,"%03d.",(U32)(val/(U64)1e6));
    val %= (U64)1e6;
    sprintf (sp,"%03d.%03d",(U32)(val/1000),(U32)(val%1000));
    return;
  }
  if (val >= (U64)1e6) {
    sp += sprintf (sp,"%d.",(U32)(val/(U64)1e6));
    val %= (U64)1e6;
    sprintf (sp,"%03d.%03d",(U32)(val/1000),(U32)(val%1000));
    return;
  }
  if (val >= 1000) {
    sprintf (sp,"%d.%03d",(U32)(val/1000),(U32)(val%1000));
    return;
  }
  sprintf (sp,"%d",(U32)(val));
}
